import {login,getUserInfo} from '@/api/user';
import {encrypt} from '@/utils/crypto';
import asideMenus from '@/config/asideMenus';
import MainConfig from '@/router/main.children';


function filterMenus(identity){
    //admin 或 consumer
    return asideMenus.filter(item => item.identity.includes(identity)).map(val => {
        val.children = val.children.filter(v => v.identity.includes(identity));

        val.children.forEach(child => {
            child.path = MainConfig.find(route => route.name === child.name).path;
        })
        return val
    })  
}

export default {
    namespaced :true,
    state: {
        userinfo:{},
        asideMenus:[]  //侧边菜单
    },
    mutations: {
        SET_USERINFO(state,payload){
            state.userinfo = payload;
        },
        SET_MENUS(state,payload){
            state.asideMenus = payload
        }
    },
    actions: {
        async login(context,{username,password}){
            let res = await login(username,password);
            if(res.data.code === 1){
                localStorage.setItem('token',res.data.data.token);
                return {code:1,msg:'登录成功'}
            }else{
                return {code:0,msg:'登录失败'}
            }
        },
        async getUserInfo({commit}){
            let result = await getUserInfo();
            if(result.data.code === 1){
                let {username,identity} = result.data.data;

                //侧边栏处理

                let menus = filterMenus(identity.name);

                commit('SET_MENUS',menus);


                localStorage.setItem('userinfo',encrypt(JSON.stringify({username,identity:identity.name})))
                commit('SET_USERINFO',{username,identity:identity.name})
            }
        }
    }
}